import re
from bs4 import BeautifulSoup

# 复制自动合并表格的函数
def convert_markdown_table_to_html(markdown_table):
    lines = markdown_table.strip().split('\n')
    if not lines or len(lines) < 3:
        return markdown_table
    
    # Parse table structure
    table_data = []
    for line in lines:
        line = line.strip()
        if not line or line.startswith('| ---'):
            continue
        if line.startswith('|'):
            # Split by '|' and strip whitespace
            cells = [cell.strip() for cell in line.split('|')[1:-1]]
            table_data.append(cells)
    
    if not table_data:
        return markdown_table
    
    # Determine column count
    col_count = max(len(row) for row in table_data)
    
    # Detect merged cells (same content in consecutive rows, same column)
    rowspan_info = [[1 for _ in range(col_count)] for _ in range(len(table_data))]
    for col in range(col_count):
        i = 0
        while i < len(table_data):
            if not table_data[i][col]:
                i += 1
                continue
            current_value = table_data[i][col]
            span = 1
            for j in range(i + 1, len(table_data)):
                if table_data[j][col] == current_value:
                    span += 1
                else:
                    break
            if span > 1:
                rowspan_info[i][col] = span
                for j in range(i + 1, i + span):
                    rowspan_info[j][col] = 0
            i += span
    
    # Generate HTML table
    html = '<table>\n'
    html += '  <thead>\n'
    # Assume first row is header
    html += '    <tr>\n'
    for cell in table_data[0]:
        html += f'      <th>{cell}</th>\n'
    html += '    </tr>\n'
    html += '  </thead>\n'
    html += '  <tbody>\n'
    
    # Body rows
    for i in range(1, len(table_data)):
        html += '    <tr>\n'
        for j in range(len(table_data[i])):
            if rowspan_info[i][j] == 0:
                continue  # Skip merged cells
            cell_content = table_data[i][j]
            if rowspan_info[i][j] > 1:
                html += f'      <td rowspan="{rowspan_info[i][j]}">{cell_content}</td>\n'
            else:
                html += f'      <td>{cell_content}</td>\n'
        html += '    </tr>\n'
    
    html += '  </tbody>\n</table>\n'
    return html

# 测试用的Markdown表格
test_table = '''| Directory | Sub-directory | Description |
| --- | --- | --- |
| Create Folder | - | Creates a new folder. |
| Create Scripts | Create Component | Creates a new script component. |
| Create Scripts | Create EventType | Creates a new event type. |
| Create Scripts | Create ItemType | Creates a new item type. |
| Create Scripts | Create BTNodeType | Creates a new BTNode type. |
| Create Scripts | Create StateType | Creates a new StateType type. |
| Create Scripts | Create StructType | Creates a new StructType type. |
| Create Scripts | Create Logic | Creates a new logic. |
| Create Scripts | Create Script | Creates a top-level script where you can input scripts from the beginning. |
| Create DataSet | - | Creates a new DataSet. |
| Create TileDataSet | - | Creates a new TileDataSet. |
| Create AtlasBlueprint | - | Creates a new AtlasBlueprint. |
| Create Material | - | Creates a new material. |
| Create Model | - | Creates a new empty model. Manually add a component. |
| Copy Entry ID | - | Copies the ID of the selected entry. |
| Import From | Import Scripts | Imports scripts from PC. |
| Import From | Import Image | Imports image file from PC. |
| Import From | Import Sound | Imports sound file from PC. |
| Import From | Import Package | Imports package from PC. |
'''

# 测试自动合并功能
print("=== 测试自动表格合并功能 ===")
print("输入Markdown表格：")
print(test_table)

# 转换为HTML
html_table = convert_markdown_table_to_html(test_table)
print("\n输出HTML表格：")
print(html_table)

# 检查合并结果
print("\n=== 验证合并结果 ===")
soup = BeautifulSoup(html_table, 'html.parser')

# 检查Create Scripts单元格合并
create_scripts_cell = soup.find('td', string='Create Scripts')
if create_scripts_cell and create_scripts_cell.get('rowspan') == '8':
    print("✓ Create Scripts单元格正确合并（rowspan=8）")
else:
    print("✗ Create Scripts单元格合并错误")

# 检查Import From单元格合并
import_from_cell = soup.find('td', string='Import From')
if import_from_cell and import_from_cell.get('rowspan') == '4':
    print("✓ Import From单元格正确合并（rowspan=4）")
else:
    print("✗ Import From单元格合并错误")

print("\n=== 测试完成 ===")
